<?php

namespace App\Services;

use App\Models\Province;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class ProvinceBatchLineSpiderService
{
    public $proxyConfig;
    public $httpClient;
    public $maxRetries = 3;
    public $proxyPool = [];
    public $currentProxyIndex = 0;

    public function __construct(bool $proxy_enable = false)
    {
        $this->proxyConfig = [
            'enable' => $proxy_enable,
            'type' => 'http', // 支持http/socks4/socks5
            'timeout' => 30,
            'retry' => 3
        ];

        $this->initHttpClient();
        $this->initProxyPool();
    }

    public function initHttpClient()
    {
        $this->httpClient = new Client([
            'timeout' => 30,
            'verify' => false,
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            ]
        ]);
    }

    public function initProxyPool()
    {
        if ($this->proxyConfig['enable']) {
            $this->proxyPool = "http://host.docker.internal:1082";
        }
    }

    public function getNextProxy()
    {
        if (empty($this->proxyPool)) {
            return null;
        }

        $proxy = $this->proxyPool[$this->currentProxyIndex];
        $this->currentProxyIndex = ($this->currentProxyIndex + 1) % count($this->proxyPool);
        
        return [
            'http' => "{$proxy['type']}://{$proxy['username']}:{$proxy['password']}@{$proxy['host']}:{$proxy['port']}",
            'https' => "{$proxy['type']}://{$proxy['username']}:{$proxy['password']}@{$proxy['host']}:{$proxy['port']}"
        ];
    }

    public function markProxyFailed($proxyId)
    {
        Proxy::where('id', $proxyId)->update([
            'failed_count' => \DB::raw('failed_count + 1'),
            'last_failed_at' => now()
        ]);
    }

    /**
     * 获取所有省份ID
     * @return array
     */
    public function getProvinceIds(): array
    {
        return Province::query()
            ->whereNotNull('gaokao_province_id')
            ->pluck('gaokao_province_id', 'id')
            ->toArray();
    }

    /**
     * 采集省份批次线数据
     * @param array $options 采集选项
     * @return array 采集结果
     */
    public function fetchProvinceBatchLines(array $options): array
    {
        $results = [];
        $provinceIds = $this->getProvinceIds();
        
        foreach ($provinceIds as $provinceId => $gaokaoId) {
            $retryCount = 0;
            $success = false;
            
            while ($retryCount < $this->maxRetries && !$success) {
                try {
                    $url = "https://static-data.gaokao.cn/www/2.0/proprovince/{$gaokaoId}/pro.json?a=www.gaokao.cn";
                    $requestOptions = ['timeout' => 30];
                    
                    if ($this->proxyConfig['enable']) {
                        $proxy = $this->getNextProxy();
                        if ($proxy) {
                            $requestOptions['proxy'] = $proxy;
                        }
                    }
                    
                    $response = $this->httpClient->get($url, $requestOptions);
                    $data = json_decode($response->getBody(), true);
                    
                    if ($data['code'] === '0000') {
                        $processed = $this->processProvinceData($provinceId, $data['data']);
                        $results[$provinceId] = count($processed);
                        $success = true;
                        
                        // 保存数据到数据库
                        $this->saveBatchLines($processed);
                    }
                } catch (GuzzleException $e) {
                    error_log("采集省份{$provinceId}失败(尝试{$retryCount}): " . $e->getMessage());
                    $retryCount++;
                    
                    if ($this->proxyConfig['enable'] && !empty($proxy)) {
                        $this->markProxyFailed($proxy['id']);
                    }
                    
                    if ($retryCount >= $this->maxRetries) {
                        error_log("省份{$provinceId}采集最终失败");
                    }
                }
            }
        }
        
        return [
            'status' => 'success',
            'total' => array_sum($results),
            'details' => $results
        ];
    }

    public function saveBatchLines(array $items)
    {
        // 分批插入数据，每批100条
        $chunks = array_chunk($items, 100);
        
        foreach ($chunks as $chunk) {
            try {
                \DB::table('province_batch_line')->insert($chunk);
            } catch (\Exception $e) {
                // 处理重复数据
                foreach ($chunk as $item) {
                    try {
                        \DB::table('province_batch_line')->updateOrInsert(
                            [
                                'province_id' => $item['province_id'],
                                'year' => $item['year'],
                                'batch' => $item['batch'],
                                'type' => $item['type']
                            ],
                            $item
                        );
                    } catch (\Exception $e) {
                        error_log("保存数据失败: " . $e->getMessage());
                    }
                }
            }
        }
    }

    /**
     * 处理省份数据
     * @param int $provinceId
     * @param array $data
     * @return array
     */
    public function processProvinceData(int $provinceId, array $data): array
    {
        $processed = [];
        
        foreach ($data as $year => $yearData) {
            foreach ($yearData as $tType => $items) {
                foreach ($items as $item) {
                    // 数据验证
                    if (empty($item['batch']) || empty($item['year'])) {
                        continue;
                    }
                    
                    $item['t_type'] = $tType;
                    $item['province_id'] = $provinceId;
                    $processed[] = $this->formatItem($item);
                }
            }
        }
        
        return $processed;
    }

    /**
     * 格式化数据项
     * @param array $item
     * @return array
     */
    public function formatItem(array $item): array
    {
        return [
            'batch' => $item['batch'] ?? null,
            'batch_name' => $item['batch_name'] ?? null,
            'convention_batch' => $item['convention_batch'] ?? null,
            'diff' => $item['diff'] ?? null,
            'major_score' => $item['major_score'] ?? null,
            'name' => $item['name'] ?? null,
            'province' => $item['province'] ?? null,
            'rank' => $item['rank'] ?? null,
            'score' => $item['score'] ?? null,
            'score_section' => $item['score_section'] ?? null,
            'type' => $item['type'] ?? null,
            'type_name' => $item['type_name'] ?? null,
            'year' => $item['year'] ?? null,
            't_type' => $item['t_type'] ?? null,
            'province_id' => $item['province_id'] ?? null,
            'created_at' => now(),
            'updated_at' => now()
        ];
    }
}
